'use strict';

const { Gateway,Wallets} = require('fabric-network');
const path = require('path');
const { getCurrentDate,buildCCPOrg2,buildWallet } = require('../../../jsUtils/AppUtil.js');

const channelName1 = 'channel1';
const channelName2 = 'channel2';
const chaincodeName = 'basic';

const walletPathOrg2 = path.join(__dirname, 'walletOrg2');

const org2d1 = 'school';
const org2d2 = 'buyer';

function prettyJSONString(inputString) {
	return JSON.stringify(JSON.parse(inputString));
}

//消费者查看在org1公司上进行的交易账本
exports.checkOrg1Transaction=async (id)=>{
	/**
	 * id=10||11||12||13
	 */
	try{
		const ccp = buildCCPOrg2();
		const wallet = await buildWallet(Wallets, walletPathOrg2);
		const gateway = new Gateway();

		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org2d2,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName1);
			const contract = network.getContract(chaincodeName);
			
			let result=await contract.evaluateTransaction('ReadAsset', id);
			var temp=result.toString();

			if(temp=="[object Object]"){
				result={
					"提示":"不存在订单号为此id的商品"
				}
				return result;
			}
			else{
				console.log(`*** Result: ${prettyJSONString(result.toString())}`);
				var resultStr=result.toString();
				return resultStr;
			}
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}

//消费者查看在org3公司上进行的交易账本
exports.checkOrg3Transaction=async (id)=>{
	/**
	 * id=10||11||12||13
	 */
	try{
		const ccp = buildCCPOrg2();
		const wallet = await buildWallet(Wallets, walletPathOrg2);
		const gateway = new Gateway();

		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org2d2,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName2);
			const contract = network.getContract(chaincodeName);
			
			let result=await contract.evaluateTransaction('ReadAsset', id);
			var temp=result.toString();

			if(temp=="[object Object]"){
				result={
					"提示":"不存在订单号为此id的商品"
				}
				return result;
			}
			else{
				console.log(`*** Result: ${prettyJSONString(result.toString())}`);
				var resultStr=result.toString();
				return resultStr;
			}
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}		
}

//org1货物运输到目的地，目的地进行确认
exports.org1Transfer2School=async (ledger)=>{
	/**
	 * ledger=[
	 * 		{
	 * 			id:10,
	 * 			amount:100,
	 * 			price:200
	 * 		},
	 * 		...
	 * ]
	 */
	try{
		const ccp = buildCCPOrg2();
		const wallet = await buildWallet(Wallets, walletPathOrg2);
		const gateway = new Gateway();

		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org2d1,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName1);
			const contract = network.getContract(chaincodeName);
			
            var arrayResult=new Array();
			for(var i=0;i<ledger.length;i++){
				console.log('\n--> Submit Transaction: TransferAsset, transfer to new owner of school');
				var date=getCurrentDate();
				let result=await contract.submitTransaction('TransferAsset', ledger[i], 'school',date);
				console.log('*** Result: committed');
				if (`${result}` !== '') {
					console.log(`*** Result: ${prettyJSONString(result.toString())}`);
					arrayResult.push(result.toString());
				}
			}
            return arrayResult;
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}

//org3货物运输到目的地，目的地进行确认
exports.org3Transfer2School=async (ledger)=>{
	/**
	 * ledger=[
	 * 		{
	 * 			id:10,
	 * 			amount:100,
	 * 			price:200
	 * 		},
	 * 		...
	 * ]
	 */
	try{
		const ccp = buildCCPOrg2();
		const wallet = await buildWallet(Wallets, walletPathOrg2);
		const gateway = new Gateway();

		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org2d1,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName2);
			const contract = network.getContract(chaincodeName);
			
            var arrayResult=new Array();
			for(var i=0;i<ledger.length;i++){
				console.log('\n--> Submit Transaction: TransferAsset, transfer to new owner of school');
				var date=getCurrentDate();
				let result=await contract.submitTransaction('TransferAsset', ledger[i], 'school',date);
				console.log('*** Result: committed');
				if (`${result}` !== '') {
					console.log(`*** Result: ${prettyJSONString(result.toString())}`);
					arrayResult.push(result.toString());
				}
			}
            return arrayResult;
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}

//org1货物被消费者收取，消费者进行确认
exports.org1School2Buyer=async (ledger)=>{
	/**
	 * ledger=[
	 * 		{
	 * 			id:10,
	 * 			amount:100,
	 * 			price:200
	 * 		},
	 * 		...
	 * ]
	 */
	try{
		const ccp = buildCCPOrg2();
		const wallet = await buildWallet(Wallets, walletPathOrg2);
		const gateway = new Gateway();

		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org2d2,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName1);
			const contract = network.getContract(chaincodeName);
			
            var arrayResult=new Array();
			for(var i=0;i<ledger.length;i++){
				console.log('\n--> Submit Transaction: TransferAsset, transfer to new owner of buyer');
				var date=getCurrentDate();
				let result=await contract.submitTransaction('TransferAsset', ledger[i], 'buyer',date);
				console.log('*** Result: committed');
				if (`${result}` !== '') {
					console.log(`*** Result: ${prettyJSONString(result.toString())}`);
					arrayResult.push(result.toString());
				}
			}
            return arrayResult;
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}

//org3货物被消费者收取，消费者进行确认
exports.org3School2Buyer=async (ledger)=>{
	/**
	 * ledger=[
	 * 		{
	 * 			id:10,
	 * 			amount:100,
	 * 			price:200
	 * 		},
	 * 		...
	 * ]
	 */
	try{
		const ccp = buildCCPOrg2();
		const wallet = await buildWallet(Wallets, walletPathOrg2);
		const gateway = new Gateway();

		try {
			await gateway.connect(ccp, {
				wallet,
				identity: org2d2,
				discovery: { enabled: true, asLocalhost: true }
			});
			const network = await gateway.getNetwork(channelName2);
			const contract = network.getContract(chaincodeName);
			
            var arrayResult=new Array();
			for(var i=0;i<ledger.length;i++){
				console.log('\n--> Submit Transaction: TransferAsset, transfer to new owner of buyer');
				var date=getCurrentDate();
				let result=await contract.submitTransaction('TransferAsset', ledger[i], 'buyer',date);
				console.log('*** Result: committed');
				if (`${result}` !== '') {
					console.log(`*** Result: ${prettyJSONString(result.toString())}`);
					arrayResult.push(result.toString());
				}
			}
            return arrayResult;
		} finally {
			gateway.disconnect();
		}
	}
	catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}
